<template>
  <q-dialog class="my-dialog-form" v-model="isFlagShow">
    <q-card class="my-card">
      <q-toolbar class="row items-center my-form-header">
        <div class="my-tableTitle">
          {{dlgTitle}}
        </div>
        <q-space />
        <q-btn flat round dense icon="mdi-close" @click="close"/>
      </q-toolbar>
      <q-separator />
      <q-card-setion class="q-mx-xs-xs">
        <q-scroll-area class="my-form-container">
          <table class="my-form-table">
            <tr class="my-row-height">
              <td class="my-label"><span style="color: red">**</span>项目名称：</td>
              <td class="my-value">
                <q-select
                  class="my-select-box"
                  dense
                  outlined
                  options-dense
                  clearable
                  :options="projectArr"
                  v-model="param.project"
                  option-value="label"
                  emit-value
                  options-selected-class="teal"
                  @blur="v$.project.$touch()"
                  :error="v$.project.$error"
                  error-message="请选择项目名称！"
                  @update:model-value="refreshProject"
                />
              </td>
              <td class="my-label"><span style="color: red">**</span>设备名称：</td>
              <td class="my-value">
                <q-select
                  dense
                  outlined
                  options-dense
                  emit-value
                  clearable
                  option-value="label"
                  :options="deviceList"
                  v-model="param.device"
                  @blur="v$.device.$touch()"
                  :error="v$.device.$error"
                  error-message="请选择设备！"
                />
              </td>
            </tr>
            <tr class="my-row-height">
              <td class="my-label"><span style="color: red">**</span>变量名称：</td>
              <td class="my-value">
                <q-input
                  outlined
                  dense
                  v-model="param.cname"
                  @blur="v$.cname.$touch()"
                  :error="v$.cname.$error"
                  error-message="请输入不少于2个字符！"
                />
              </td>
              <td class="my-label"><span style="color: red">**</span>变量类型：</td>
              <td class="my-value">
                <q-select
                  dense
                  outlined
                  options-dense
                  clearable
                  :options="varTypeArr"
                  option-value="label"
                  emit-value
                  v-model="param.ioType"
                  @blur="v$.ioType.$touch()"
                  :error="v$.ioType.$error"
                  error-message="请选择变量地址！"
                />
              </td>
            </tr>
            <tr class="my-row-height">
              <td class="my-label"><span style="color: red">**</span>IO地址[0~255]：</td>
              <td class="my-value">
                <q-input
                  outlined
                  dense
                  type="number"
                  v-model="param.ioAddr"
                  @blur="v$.ioAddr.$touch()"
                  :error="v$.ioAddr.$error"
                  error-message="请输入IO地址！"
                />
              </td>
              <td class="my-label">变量序码：</td>
              <td class="my-value">
                <q-input
                  outlined
                  dense
                  v-model="param.sortCode"
                  @blur="v$.sortCode.$touch()"
                  :error="v$.sortCode.$error"
                  error-message="请输入不少于2个字符！"
                />
              </td>
            </tr>
            <tr class="my-row-height">
              <td class="my-label">变量最小值：</td>
              <td class="my-value">
                <q-input
                  outlined
                  dense
                  type="number"
                  v-model.lazy.number="param.ioMin"
                />
              </td>
              <td class="my-label">变量最大值：</td>
              <td class="my-value">
                <q-input
                  outlined
                  dense
                  type="number"
                  v-model.lazy.number="param.ioMax"
                />
              </td>
            </tr>
            <tr class="my-row-height">
              <td class="my-label">报警最小值：</td>
              <td class="my-value">
                <q-input
                  outlined
                  dense
                  type="number"
                  v-model.lazy.number="param.alarmMin"
                />
              </td>
              <td class="my-label">报警最大值：</td>
              <td class="my-value">
                <q-input
                  outlined
                  dense
                  type="number"
                  v-model.lazy.number="param.alarmMax"
                />
              </td>
            </tr>
            <tr class="my-row-height">
              <td class="my-label">采样周期：</td>
              <td class="my-value">
                <q-input
                  outlined
                  dense
                  type="number"
                  v-model.lazy.number="param.collectPeriod"
                />
              </td>
              <td class="my-label">存储周期：</td>
              <td class="my-value">
                <q-input
                  outlined
                  dense
                  type="number"
                  v-model.lazy.number="param.storePeriod"
                />
              </td>
            </tr>
            <tr class="my-row-height">
              <td class="my-label">公式类型：</td>
              <td class="my-value">
                <q-select
                  dense
                  outlined
                  options-dense
                  :options="formulaArr"
                  v-model="param.formula"
                  option-value="label"
                  emit-value
                  options-selected-class="teal"
                />
              </td>
              <td class="my-label">操作类型：</td>
              <td class="my-value">
                <q-select
                  dense
                  outlined
                  options-dense
                  :options="operationArr"
                  v-model="param.operation"
                  option-value="label"
                  emit-value
                  options-selected-class="teal"
                />
              </td>
            </tr>
            <tr class="my-row-height">
              <td class="my-label">是否报警：</td>
              <td class="my-value">
                <q-toggle
                  v-model="param.isAlarm"
                  true-value="1"
                  false-value="0"
                  color="green"
                  label="允许报警"
                />
              </td>
              <td class="my-label">是否存储：</td>
              <td class="my-value">
                <q-toggle
                  v-model="param.isStore"
                  true-value="1"
                  false-value="0"
                  color="green"
                  label="允许存储"
                />
              </td>
            </tr>
          </table>
        </q-scroll-area>
      </q-card-setion>
      <q-separator />
      <div class="q-gutter-sm my-form-footer">
        <q-btn
          unelevated
          dense
          label="提交"
          type="submit"
          color="teal-3"
          @click="onSubmit"
          style="width: 80px"
        />
        <q-btn
          unelevated
          dense
          label="重置"
          type="reset"
          color="orange-3"
          @click="onReset"
          style="width: 80px"
        />
      </div>
    </q-card>
  </q-dialog>
</template>

<script lang="ts">
import { defineAsyncComponent, defineComponent, onMounted, ref, toRef, toRefs, PropType, watch } from 'vue';
import { isObjectEmpty } from '../../../util/utils';
import { required, minLength } from '@vuelidate/validators'
import { useVuelidate } from '@vuelidate/core';
import { cataItem } from '../../../hook/common/useCatalogType';
import { useCatalogTool } from 'src/hook/common/useCatalogTool';
import { useRoute } from 'vue-router';
import useCommonVisitDatabase from 'src/hook/common/useCommonVisitDatabase';
import api from 'axios';

import { VariableItem, VariableItemVO } from './VariableModel';
import { scaBaseVOAPI } from 'src/util/ScaBaseConst';


export default defineComponent({
  cname: 'VariableDlgBak',
  components: {

  },
  props: {
    itemData: {
      type: Object as PropType<VariableItem>,
      required: true
    },

    projectArr: {
      type: Array as PropType<cataItem[]>,
      required: true
    },

    deviceArr: {
      type: Array as PropType<cataItem[]>,
      required: true
    },

    ioAddrArr: {
      type: Array as PropType<cataItem[]>,
      default: () => {
        return [];
      }
    },

    varTypeArr: {
      type: Array as PropType<cataItem[]>,
      required: true
    },

    varUnitArr: {
      type: Array as PropType<cataItem[]>,
      required: true
    },

    formulaArr: {
      type: Array as PropType<cataItem[]>,
      required: true
    },

    operationArr: {
      type: Array as PropType<cataItem[]>,
      required: true
    }
  },
  emits: ['submit-variable-item', 'cancel-variable-item'],
  setup (props, context) {
    //数据解构
    const {
      itemData,
      projectArr,
      deviceArr,
      varTypeArr,
      varUnitArr,
      formulaArr,
      operationArr
    } = toRefs(props);

    //*******************************
    //      目录操作
    //*******************************
    const {
      findCatalogLabel,
      findCatalogId
    } = useCatalogTool();


    //*******************************
    //      表单项
    //*******************************
    //窗口显示
    let isFlagShow = ref(false);

    //窗口标题
    let dlgTitle = ref('');

    //界面数据
    let param = ref<VariableItemVO>({
      id: 0,
      cname: '',
      project: '',
      device: '',
      ioAddr: 0,
      ioType: '',
      ioUnit: '',
      ioMin: 0,
      ioMax: 0,
      alarmMin: 0,
      alarmMax: 0,
      formula: '',
      operation: '',
      isAlarm: false,
      isStore: false,
      collectPeriod: 0,
      storePeriod: 0,
      sortCode: '',
      description: ''
    });

    //设备列表
    let deviceList = ref<cataItem[]>([]);


    //关闭窗口
    const close = () => {
      isFlagShow.value = false;
      context.emit('cancel-variable-item');
    }

    //显示窗口
    const show = (text: string) => {
      isFlagShow.value = true;
      dlgTitle.value = text;
    }

    //提交窗口
    const onSubmit = () => {
      v$.value.$validate();
      if (v$.value.$error) {
        alert('输入参数校验错误!');
      } else {
        isFlagShow.value = false;
        let item: VariableItem = {
          id: param.value.id,
          cname: param.value.cname,
          projectId: findCatalogId(projectArr.value, param.value.project),
          deviceId: findCatalogId(deviceArr.value, param.value.device),
          ioAddr: param.value.ioAddr,
          ioTypeId: findCatalogId(varTypeArr.value, param.value.ioType),
          ioUnitId: findCatalogId(varUnitArr.value, param.value.ioUnit),
          ioMin: param.value.ioMin,
          ioMax: param.value.ioMax,
          alarmMin: param.value.alarmMin,
          alarmMax: param.value.alarmMax,
          formulaId: findCatalogId(formulaArr.value, param.value.formula),
          operationId: findCatalogId(operationArr.value, param.value.operation),
          isAlarm: param.value.isAlarm,
          isStore: param.value.isStore,
          collectPeriod: param.value.collectPeriod,
          storePeriod: param.value.storePeriod,
          sortCode: param.value.sortCode,
          description: param.value.description,
          createTime: '',
          createUserId: 0,
          updateTime: '',
          updateUserId: 0
        };

        //发送消息
        context.emit('submit-variable-item', item);
      }
    }

    //重置
    const onReset = () => {
      if (param.value) {
        param.value.id = 0;
        param.value.cname = '';
        param.value.project = '';
        param.value.device = '';
        param.value.ioAddr = 0;
        param.value.ioType = '';
        param.value.ioUnit = '';
        param.value.ioMin = 0;
        param.value.ioMax = 0;
        param.value.alarmMin = 0;
        param.value.alarmMax = 0;
        param.value.formula = '';
        param.value.operation = '';
        param.value.isAlarm = false;
        param.value.isStore = false;
        param.value.collectPeriod = 0;
        param.value.storePeriod = 0;
        param.value.sortCode = '';
        param.value.description = '';
      }

      //表单验证初始化
      v$.value.$reset();
    }

    //项目列表选择更新
    const refreshProject = () => {
      let projectId = findCatalogId(projectArr.value, param.value.project);
      if (projectId === -1) {
        alert('error')
        return;
      }
      
      api.post(scaBaseVOAPI.SCA_DEVICE_SEARCH_LIST_API, {
        id: projectId
      }).then((res) => {
        if (res.data.message === 'Success') {
          let arr: cataItem[] = res.data.data;
          deviceList.value.length = 0;
          arr.forEach((item) => {
            deviceList.value.push(item);
          })
        }
      })
    }


    //*******************************
    //      表单校验
    //*******************************
    //配置校验规则
    const rules = {
      id: {},
      cname: { required, minLength: minLength(2) },
      project: {},
      device: {},
      ioAddr: { required },
      ioType: { required },
      ioUnit: {},
      ioMin: {},
      ioMax: {},
      alarmMin: {},
      alarmMax: {},
      formula: {},
      operation: {},
      isAlarm: {},
      isStore: {},
      collectPeriod: {},
      storePeriod: {},
      sortCode: {},
      description: {}
    }

    //使用vuelidate，建立变量对应的校验规则
    const v$ = useVuelidate(rules, {
      id: toRef(param.value, 'id'),
      cname: toRef(param.value, 'cname'),
      project: toRef(param.value, 'project'),
      device: toRef(param.value, 'device'),
      ioAddr: toRef(param.value, 'ioAddr'),
      ioType: toRef(param.value, 'ioType'),
      ioUnit: toRef(param.value, 'ioUnit'),
      ioMin: toRef(param.value, 'ioMin'),
      ioMax: toRef(param.value, 'ioMax'),
      alarmMin: toRef(param.value, 'alarmMin'),
      alarmMax: toRef(param.value, 'alarmMax'),
      formula: toRef(param.value, 'formula'),
      operation: toRef(param.value, 'operation'),
      isAlarm: toRef(param.value, 'isAlarm'),
      isStore: toRef(param.value, 'isStore'),
      collectPeriod: toRef(param.value, 'collectPeriod'),
      storePeriod: toRef(param.value, 'storePeriod'),
      sortCode: toRef(param.value, 'sortCode'),
      description: toRef(param.value, 'description')
    });


    //*******************************
    //      启动模块
    //*******************************
    //初始化
    const init = () => {
      if (!isObjectEmpty(itemData.value)) {
        param.value.id = itemData.value.id;
        param.value.cname = itemData.value.cname;
        param.value.project = findCatalogLabel(projectArr.value, itemData.value.projectId);
        param.value.device = findCatalogLabel(deviceArr.value, itemData.value.deviceId);
        param.value.ioAddr = itemData.value.ioAddr;
        param.value.ioType = findCatalogLabel(varTypeArr.value, itemData.value.ioTypeId);
        param.value.ioUnit = findCatalogLabel(varUnitArr.value, itemData.value.ioUnitId);
        param.value.ioMin = itemData.value.ioMin;
        param.value.ioMax = itemData.value.ioMax;
        param.value.alarmMin = itemData.value.alarmMin;
        param.value.alarmMax = itemData.value.alarmMax;
        param.value.formula = findCatalogLabel(formulaArr.value, itemData.value.formulaId);
        param.value.operation = findCatalogLabel(operationArr.value, itemData.value.operationId);
        param.value.isAlarm = itemData.value.isAlarm;
        param.value.isStore = itemData.value.isStore;
        param.value.collectPeriod = itemData.value.collectPeriod;
        param.value.storePeriod = itemData.value.storePeriod;
        param.value.sortCode = itemData.value.sortCode;
        param.value.description = itemData.value.description;
      }

      deviceList.value.length = 0;
      deviceArr.value.forEach((item) => {
        deviceList.value.push(item);
      })

      //表单验证初始化
      v$.value.$reset();
    }

    //监听对象的所有属性
    watch(() => props.itemData, () => {
      init();
    }, { deep: true });

    //启动挂载组件
    onMounted(() => {
      init();
    })

    return {
      itemData,
      projectArr,
      varTypeArr,
      varUnitArr,
      formulaArr,
      operationArr,

      isFlagShow,
      dlgTitle,
      param,
      deviceList,
      init,
      close,
      show,
      onSubmit,
      onReset,
      v$,

      refreshProject
    }
  }
})
</script>

<style lang="scss" scoped>
.my-card {
  alignment: center;
  width: 800px;
  max-width: 900px;
  .my-form-container {
    text-align: center;
    padding: 5px 50px 5px 50px;
    height: 450px;

    .my-select-box {
      max-width: 218px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
}

</style>
